import React, { useState, useEffect, useRef } from "react";
import { Avatar, NavBar, TabBar, SearchBar, CapsuleTabs } from "antd-mobile";
import { BellOutline, TagOutline, StarOutline } from "antd-mobile-icons";
import { useLocation, useNavigate } from "react-router-dom";
import { Swiper, SwiperSlide } from "swiper/react";
import axios from "axios";
import store from "../../redux";
import "../../css/zxx/Shou.css";
import "swiper/swiper-bundle.css";
import "./iconfont/iconfont.css";

function Shou() {
  const [type, setType] = useState([
    {
      id: 1,
      name: "清洁服务",
      img: "/清洁.png",
      key: "qingjie",
      backcolor: "#f4ecff",
    },
    {
      id: 2,
      name: "维修服务",
      img: "/维修.png",
      key: "weixiu",
      backcolor: "#fff7eb",
    },
    {
      id: 3,
      name: "粉刷服务",
      img: "/粉刷.png",
      key: "fenshua",
      backcolor: "#eff3ff",
    },
    {
      id: 4,
      name: "洗衣服务",
      img: "/洗衣机.png",
      key: "xiyi",
      backcolor: "#fffbed",
    },
    {
      id: 5,
      name: "家电维修",
      img: "/家电维修.png",
      key: "jiadian",
      backcolor: "#fff2f2",
    },
    {
      id: 6,
      name: "管道维修",
      img: "/管道.png",
      key: "guandao",
      backcolor: "#f1f9f1",
    },
    {
      id: 7,
      name: "搬家服务",
      img: "/搬家运输.png",
      key: "banjia",
      backcolor: "#ebfafc",
    },
  ]);
  const [user, setUser] = useState({});
  const [greeting, setGreeting] = useState("");
  const navigate = useNavigate();
  //   const [list, setList] = useState([
  //     {
  //       id: 1,
  //       name: "徐心怡",
  //       con: "房屋清洁",
  //       price: "249",
  //       rate: 4.8,
  //       ping: 8289,
  //       collect: false,
  //       img: "../listimgs/房屋清洁.jpeg",
  //       type: "qingjie",
  //     },
  //     {
  //       id: 2,
  //       name: "徐心怡",
  //       con: "衣物清洁",
  //       price: "345",
  //       rate: 4.8,
  //       ping: 8289,
  //       collect: false,
  //       img: "../listimgs/衣物清洁1.jpeg",
  //       type: "xiyi",
  //     },
  //     {
  //       id: 3,
  //       name: "徐心怡",
  //       con: "浴室清洁",
  //       price: "150",
  //       rate: 5.8,
  //       ping: 4567,
  //       collect: true,
  //       img: "../listimgs/浴室清洁.jpeg",
  //       type: "qingjie",
  //     },
  //     {
  //       id: 4,
  //       name: "徐心怡",
  //       con: "地板清洁",
  //       price: "210",
  //       rate: 3.1,
  //       ping: 8765,
  //       collect: false,
  //       img: "../listimgs/地板清洁.jpeg",
  //       type: "qingjie",
  //     },
  //     {
  //       id: 5,
  //       name: "王小小",
  //       con: "衣物清洁",
  //       price: "210",
  //       rate: 3.1,
  //       ping: 8765,
  //       collect: true,
  //       img: "../listimgs/衣物清洁1.jpeg",
  //       type: "xiyi",
  //     },
  //     {
  //       id: 6,
  //       name: "王小小",
  //       con: "墙面粉刷",
  //       price: "210",
  //       rate: 3.1,
  //       ping: 8765,
  //       collect: false,
  //       img: "../listimgs/房屋清洁.jpeg",
  //       type: "fenshua",
  //     },
  //     {
  //       id: 7,
  //       name: "李娜娜",
  //       con: "电器维修",
  //       price: "210",
  //       rate: 3.1,
  //       ping: 8765,
  //       collect: false,
  //       img: "../listimgs/地板清洁.jpeg",
  //       type: "weixiu",
  //     },
  //   ]);

  const [list, setList] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const pageSize = 4;

  const fetchData = async (pageNum = 1) => {
    try {
      setLoading(true);
      const response = await axios.get(
        `http://localhost:3000/clear/list?page=${pageNum}&pageSize=${pageSize}`,
        {
          headers: {
            authorization: localStorage.getItem("token"),
          },
        }
      );
      if (response.data.code === 200) {
        const newData = response.data.data;
        if (pageNum === 1) {
          setList(newData);
        } else {
          setList((prev) => [...prev, ...newData]);
        }
        // 判断是否还有更多数据
        setHasMore(newData.length === pageSize);
        setPage(pageNum);
      }
    } catch (error) {
      console.error("获取数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData(1);
  }, []);

  useEffect(() => {
    const container = document.getElementsByClassName("bigbox")[0];
    if (container) {
      const handleScroll = () => {
        const scrollTop = container.scrollTop;
        const clientHeight = container.clientHeight;
        const scrollHeight = container.scrollHeight;

        // 当滚动到底部时加载更多数据
        if (
          scrollTop + clientHeight + 30 > scrollHeight &&
          hasMore &&
          !loading
        ) {
          fetchData(page + 1);
        }
      };

      container.addEventListener("scroll", handleScroll);
      return () => {
        container.removeEventListener("scroll", handleScroll);
      };
    }
  }, [hasMore, loading, page]);

  useEffect(() => {
    axios
      .get("http://localhost:3000/name", {
        params: {
          email: localStorage.getItem("lemail"),
          phone: localStorage.getItem("lphone"),
        },
      })
      .then((res) => {
        console.log(res.data, 11111111111);
        setUser(res.data.data);
      });

    const currentHour = new Date().getHours();
    if (currentHour < 12) {
      setGreeting("早上好");
    } else if (currentHour < 15) {
      setGreeting("中午好");
    } else if (currentHour < 20) {
      setGreeting("下午好");
    } else {
      setGreeting("晚上好");
    }
  }, []);

  const images = [
    "../listimgs/地板清洁.jpeg",
    "../listimgs/房屋清洁.jpeg",
    "../listimgs/浴室清洁.jpeg",
  ];

  const [activeKey, setActiveKey] = useState("all"); // 胶囊选项卡默认选中项
  const tabss = [
    { key: "all", title: "全部" },
    { key: "qingjie", title: "清洁服务" },
    { key: "weixiu", title: "维修服务" },
    { key: "fenshua", title: "粉刷服务" },
    { key: "xiyi", title: "洗衣服务" },
  ];

  const containerRef = useRef(null);
  let start_x;
  let start_y;
  useEffect(() => {
    const container = containerRef.current;

    const touchStartHandler = (e) => {
      start_x = e.touches[0].pageX;
      start_y = e.touches[0].pageY;
    };

    const touchEndHandler = (e) => {
      const end_x = e.changedTouches[0].pageX;
      const end_y = e.changedTouches[0].pageY;
      if (start_y - end_y > 100) {
        console.log("上拉");
      } else if (end_y - start_y > 100) {
        console.log("下拉操作");
      }
    };

    if (container) {
      container.addEventListener("touchstart", touchStartHandler);
      container.addEventListener("touchend", touchEndHandler);
    }

    return () => {
      if (container) {
        container.removeEventListener("touchstart", touchStartHandler);
        container.removeEventListener("touchend", touchEndHandler);
      }
    };
  }, []);

  return (
    <div className="bigbox">
      <div className="zx-topbox">
        <div className="zx-touxiang">
          <Avatar
            src={"http://localhost:3000/" + user.img}
            className="avatar"
          />
          <p className="zx-txtext">
            {greeting}
            <br />
            <span>{user.name}</span>
          </p>
        </div>
        <div>
          <BellOutline fontSize={28} onClick={() => navigate("/zxmessage")} />
          &nbsp;&nbsp;&nbsp;
          <img
            className="zx_top_img"
            src="../../czs_imgs/收藏1.png"
            alt=""
            onClick={() => navigate("/collect")}
          />
        </div>
      </div>
      <SearchBar
        placeholder="搜索"
        onFocus={() => navigate("/search")}
        className="zx-sousuo"
      />
      <div>
        <div className="zx-accenter">
          <p className="zx-active">活动中心</p>
        </div>
        <Swiper>
          {images.map((src, index) => (
            <SwiperSlide key={index}>
              <img src={src} alt={`Slide ${index}`} className="zx-lbimg" />
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
      <div>
        <p className="zx-active">服务类型</p>
        <div className="zx-fuwu">
          {type.map((item) => {
            return (
              <dl key={item.id} className="zx-fwitem">
                <dt
                  className="czs_item_backcolor"
                  onClick={() => {
                    navigate("/Czs_typelist", {
                      state: { id: item.id, name: item.name },
                    });
                  }}
                  style={{ backgroundColor: item.backcolor }}
                >
                  <img
                    className="czs_type_img"
                    src={"../../czs_imgs" + item.img}
                    alt=""
                  />
                </dt>
                <dd
                  style={{
                    fontSize: "14px",
                    fontWeight: "600",
                    marginTop: "10px",
                  }}
                >
                  {item.name}
                </dd>
              </dl>
            );
          })}
          <div className="zx-fuwu2">
            <div
              className="zs-fuwu-2"
              onClick={() => {
                navigate("/czs_type");
              }}
            >
              <i className="iconfont icon-more" style={{ color: "purple" }}></i>
              <br />
            </div>
            <span className="zx-fwtext">更多</span>
          </div>
        </div>
      </div>
      <div>
        <div className="zx-accenter">
          <p className="zx-active">活动中心</p>
          <p className="zx-accenter-all">查看全部</p>
        </div>
        <CapsuleTabs defaultActiveKey={activeKey} onChange={setActiveKey}>
          {tabss.map((tab) => (
            <CapsuleTabs.Tab key={tab.key} title={tab.title}></CapsuleTabs.Tab>
          ))}
        </CapsuleTabs>
        <div>
          {list
            .filter((item) => {
              if (activeKey === "all") {
                return true;
              }
              return item.type === activeKey;
            })
            .map((item1) => (
              <div key={item1.id} className="service-item">
                <div>
                  <img src={item1.img} alt="" className="zx-imgqx" />
                </div>
                <div>
                  <p className="zx-qxperson">{item1.name}</p>
                  <p className="zx-qxtitle">{item1.con}</p>
                  <p className="zx-qxprice">￥{item1.price}</p>
                  <p className="zx-qxping">
                    <StarOutline style={{ color: "orange" }} />
                    {item1.rate}&nbsp;&nbsp;|&nbsp;&nbsp;{item1.ping}评价
                  </p>
                </div>
                <div className="zx-qxcollect">
                  {item1.collect == false ? (
                    <img
                      className="zx_top_img"
                      src="../../czs_imgs/收藏1.png"
                      alt=""
                    />
                  ) : (
                    <img
                      className="zx_top_img"
                      src="../../czs_imgs/收藏选中.png"
                      alt=""
                    />
                  )}
                </div>
              </div>
            ))}
          {loading && <div className="loading-text">加载中...</div>}
          {!hasMore && list.length > 0 && (
            <div className="no-more-text">没有更多数据了</div>
          )}
        </div>
      </div>
    </div>
  );
}

export default Shou;
